<template>
  <div>
    <div class="box" v-if="!isEditing">
      <div class="content">
        <ArticleTable 
          :query-params="queryParams"
          :loading="loading"
          :total="total"
          :table-data="tableData"
          @refresh="getArticleList" />
      </div>
      <div class="button">
        <el-button type="primary" @click="showEditPage">新增</el-button>
      </div>
    </div>

    <!-- 编辑页面 -->
    <div class="edit-page" v-else>
      <div class="edit-header">
        <el-button @click="backToList">返回列表</el-button>
        <h2>新增文章</h2>
      </div>
      
      <div class="edit-content">
        <el-form :model="articleForm" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="articleForm.title" placeholder="请输入标题"/>
          </el-form-item>

          <el-form-item label="文章内容" prop="content">
            <el-input
              v-model="articleForm.content"
              type="textarea"
              :rows="15"
              placeholder="请输入文章内容"/>
          </el-form-item>

          <el-form-item label="封面图片" prop="pic_url">
            <el-upload
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :on-change="handleImageChange"
              :limit="1"
              list-type="picture-card">
              <template #default>
                <el-icon><Plus /></el-icon>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <div class="edit-footer">
        <el-button @click="backToList">取消</el-button>
        <el-button type="primary" @click="handleSubmit">发布</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import ArticleTable from './articleTable.vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/info'
import type { FormInstance, FormRules } from 'element-plus'
import type { ArticleData, QueryParams } from '@/api/article/types'
import ArticleApi from '@/api/article'

const userInfoStore = useUserInfoStore()
const formRef = ref<FormInstance>()
const isEditing = ref(false)
const loading = ref(false)
const total = ref(0)
const tableData = ref<ArticleData[]>([])

// 查询参数
const queryParams = reactive<QueryParams>({
  Page: 1,
  Size: 10,
  publisher_id: Number(userInfoStore.userInfo.user_id),
  title: '',
  is_delete: 0
})

// 文章表单
const articleForm = reactive<ArticleData>({
  article_id: 0,
  publisher_id: Number(userInfoStore.userInfo.user_id),
  title: '',
  content: '',
  pic_url: '',
  review_status: 0,
  is_recommend: 0,
  is_delete: 0
})

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
})

// 显示编辑页面
const showEditPage = () => {
  isEditing.value = true
  resetForm()
}

// 返回列表
const backToList = () => {
  isEditing.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  articleForm.pic_url = ''
}

// 处理图片上传
const handleImageChange = (file: any) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    articleForm.pic_url = reader.result as string
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await ArticleApi.createArticle(articleForm)
        if (res.data ) {
          ElMessage.success('发布成功')
          backToList()
        } else {
          ElMessage.error( '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        ElMessage.error('发布失败')
      }
    }
  })
}

// 获取文章列表
const getArticleList = async () => {
  loading.value = true
  try {
    const res = await ArticleApi.getArticles(queryParams)
    if (res.data) {
      tableData.value = res.data.list
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.box {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: center; /* 修改为居中对齐 */
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px; /* 两侧添加padding */
}

.header-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.content {
  margin: 20px 0;
}

.button {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-input) {
  width: 200px;
}

.iten-text {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}
</style>

